import time
import sys
import shutil
import tempfile
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService


@pytest.fixture
def driver_setup_teardown():
    # Selenium Manager 自动管理驱动 （pip install webdriver-manager）
    # 需要翻墙https://chromedriver.storage.googleapis.com
    # driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

    # 本地驱动
    driver = webdriver.Chrome(service=ChromeService(executable_path="../data/chromedriver"))
    driver.implicitly_wait(5)
    yield driver
    # if sys.exc_info()[0]:
    #     print(sys.exc_info())
    #     timestamp = time.strftime("%Y%m%d-%H%M%S")
    #     driver.save_screenshot(f"../data/failshot_{timestamp}.png")
    driver.quit()


@pytest.fixture
def driver_download_dir_setup_teardown():
    download_dir = tempfile.mkdtemp()
    options = webdriver.ChromeOptions()
    prefs = {
        "download.default_directory": download_dir,
        "download.prompt_for_download": False,  # 自动下载，不提示
        "download.directory_upgrade": True,  # 如果目录不存在，则创建
        "safebrowsing.enabled": True  # 禁用安全浏览功能
    }
    options.add_experimental_option("prefs", prefs)
    service = ChromeService(executable_path="../data/chromedriver")
    driver = webdriver.Chrome(service=service, options=options)
    driver.implicitly_wait(5)
    yield driver, download_dir
    if sys.exc_info():
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        driver.save_screenshot(f"failshot_{timestamp}.png")
    driver.quit()
    shutil.rmtree(download_dir)
